package com.ruoyi.generator.service;

import com.ruoyi.generator.entity.*;
import com.ruoyi.generator.entity.bo.PlanScheduleInfoBO;
import com.ruoyi.generator.mapper.AppMapper;
import com.ruoyi.generator.mapper.MaintenanceMapper;
import com.ruoyi.generator.mapper.PlanScheduleMapper;
import com.ruoyi.generator.mapper.UserMsgMapper;
import com.ruoyi.generator.vo.MaintenanceAppVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public  class AppServiceImpl implements AppService {


    @Autowired
    private AppMapper appMapper;
    @Autowired
    private MaintenanceMapper maintenanceMapper;
    @Autowired
    private PlanScheduleMapper planScheduleMapper;
    @Autowired
    private UserMsgMapper userMsgMapper;


    @Override
    public List<MaintenanceAppVO> getMaintenanceList(String type) {
        if(type.equals("pending")){
            type="4";
        }
        if(type.equals("progress")){
            type="1";
        }
        if(type.equals("expired")){
            type="2";
        }
        List<MaintenanceAppVO>  maintenanceList= appMapper.getMaintenanceList(type);
//        for( MaintenanceAppVO maintenanceAppVO: maintenanceList ){
//            // 新增日期校验逻辑
//            if("pending".equals(type)){
//                if (checkExpiry(maintenanceAppVO.getStartDate(),maintenanceAppVO.getTime())&&maintenanceAppVO.getMaintenanceStatus().equals("0")) {
//                    returnList.add(maintenanceAppVO);
//                }
//            } else if ("progress".equals(type)){
//                if (maintenanceAppVO.getMaintenanceStatus().equals("1")){
//                    returnList.add(maintenanceAppVO);
//                }
//            } else if ("expired".equals(type)){
//                if(maintenanceAppVO.getMaintenanceStatus().equals("2")){
//                    returnList.add(maintenanceAppVO);
//                    continue;
//                }
//                // 当判定为过期时更新状态为2
//                if (!checkExpiry(maintenanceAppVO.getStartDate(),maintenanceAppVO.getTime())
//                    && maintenanceAppVO.getMaintenanceStatus().equals("0")) {
//                    MaintenanceAppVO vo = new MaintenanceAppVO();
//                    vo.setMaintenanceId(maintenanceAppVO.getMaintenanceId());
//                    vo.setMaintenanceStatus("2");
//                    // 更新数据库状态
//                    appMapper.updateMaintenanceStatus(vo);
//                    // 更新VO对象状态保持数据一致
//                    maintenanceAppVO.setMaintenanceStatus("2");
//                    returnList.add(maintenanceAppVO);
//                }
//            } else {
//                returnList=null;
//            }
//        }
        return maintenanceList;
    }

    /**
     * 新增时间范围判断逻辑
     */
    private boolean checkExpiry(Date targetDate, String timeRange) {
        // 原始日期校验（保持原有逻辑）
        LocalDate localTargetDate = Instant.ofEpochMilli(targetDate.getTime())
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        if (!LocalDate.now().isAfter(localTargetDate) && !LocalDate.now().isEqual(localTargetDate)) {
            return false;
        }

        // 新增时间范围校验
        LocalDateTime now = LocalDateTime.now();
        if (timeRange == null) return false;

        if (timeRange.contains("-")) {
            String[] parts = timeRange.split("-");
            if (timeRange.contains(":")) { // 处理每日时段 00:00-02:00
                LocalTime start = LocalTime.parse(parts[0].trim());
                LocalTime end = LocalTime.parse(parts[1].trim());
                return !now.toLocalTime().isBefore(start) && !now.toLocalTime().isAfter(end);
            } else if (timeRange.contains("月")) { // 处理每月/每年日期范围
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M月d日");
                LocalDate startDate = LocalDate.parse(parts[0].trim(), formatter);
                LocalDate endDate = LocalDate.parse(parts[1].trim(), formatter);
                return !now.toLocalDate().isBefore(startDate) && !now.toLocalDate().isAfter(endDate);
            }
        } else if (timeRange.startsWith("周")) { // 处理周范围
            String[] weekDays = timeRange.replace("周", "").split("到");
            if (weekDays.length == 2) {
                int startDay = convertChineseWeekday(weekDays[0].trim());
                int endDay = convertChineseWeekday(weekDays[1].trim());
                int currentDay = now.getDayOfWeek().getValue();
                return currentDay >= startDay && currentDay <= endDay;
            }
            return false;
        } else if (timeRange.contains("季度")||timeRange.contains("年")) {
            return true;
        }
        return false;
    }

    /**
     * 新增中文星期转换方法
     */
    private int convertChineseWeekday(String chineseWeekday) {
        switch (chineseWeekday) {
            case "一": return DayOfWeek.MONDAY.getValue();
            case "二": return DayOfWeek.TUESDAY.getValue();
            case "三": return DayOfWeek.WEDNESDAY.getValue();
            case "四": return DayOfWeek.THURSDAY.getValue();
            case "五": return DayOfWeek.FRIDAY.getValue();
            case "六": return DayOfWeek.SATURDAY.getValue();
            case "日": return DayOfWeek.SUNDAY.getValue();
            default: throw new IllegalArgumentException("无效的中文星期格式");
        }
    }

    /**
     * app保养提交按钮 修改问题状态
     *
     * @param maintenanceAppVO1
     * @return
     */
    @Override
    public int editMaintenance(MaintenanceAppVO maintenanceAppVO1) {
        MaintenanceAppVO maintenanceAppVO=appMapper.getMaintenanceById(maintenanceAppVO1);
        if(maintenanceAppVO1.getProblemStatus().equals("无问题")){
            maintenanceAppVO1.setMaintenanceStatus("1");
            maintenanceAppVO.setMaintenanceStatus("1");
            MaintenancePlanHistory m=new MaintenancePlanHistory();
            m.setMaintenanceId(maintenanceAppVO.getMaintenanceId());
            m.setEquipmentId(maintenanceAppVO.getEquipmentId());
            m.setIsDelete(maintenanceAppVO.getIsDelete());
            m.setMaintenancePoint(maintenanceAppVO.getMaintenancePoint());
            m.setMaintenanceItem(maintenanceAppVO.getMaintenanceItem());
            m.setSetValue(maintenanceAppVO.getSetValue());
            m.setMaintenancePeriod(maintenanceAppVO.getMaintenancePeriod());
            m.setStartDate(maintenanceAppVO.getStartDate());
            m.setMaintenanceStatus(maintenanceAppVO.getMaintenanceStatus());
            m.setTime(maintenanceAppVO.getTime());
            m.setName(maintenanceAppVO.getName());
            m.setRemark(maintenanceAppVO.getRemark());
            m.setProblemStatus(maintenanceAppVO.getProblemStatus());
            m.setType(maintenanceAppVO.getType());
            maintenanceMapper.insertWushuiMaintenancePlanHistory(m);
            return appMapper.updateMaintenanceProblemStatus(maintenanceAppVO1);
        }else {
            return appMapper.updateMaintenanceProblemStatus(maintenanceAppVO);
        }
    }

    @Override
    public List<Equipment> getEquipmentByAreaId(String areaId) {
        List<Equipment> equipment = appMapper.getEquipmentByAreaId(areaId);
        return equipment;
    }
    @Override
    public List<Area> getAreaList() {
        List<Area> areaList = appMapper.getAreaList();
        return areaList;
    }
    @Override
    public List<ClUser> getClUserList() {
        List<ClUser> clList = appMapper.getClUserList();
        return clList;
    }
    /**
     * 根据设备编号获取设备检测信息
     *
     * @param planAssociation
     * @return
     */
    @Override
    public List<PlanScheduleInfoBO> getEquipmentPlanInfo(PlanAssociation planAssociation) {
        List<PlanScheduleInfoBO> planSchedules = planScheduleMapper.selectEquipmentPlanInfo(planAssociation);
        return planSchedules;
    }

    @Override
    public ImportWaterQuality getExportWaterData() {
        ImportWaterQuality importWaterQuality = planScheduleMapper.getExportWaterData();
        return importWaterQuality;
    }

    @Override
    public ImportWaterQuality getImportWaterData() {
        ImportWaterQuality importWaterQuality = planScheduleMapper.getImportWaterData();
        return importWaterQuality;
    }

    @Override
    public void addMsg(UserMsg userMsg) {
        userMsgMapper.addMsg(userMsg);
    }
    @Override
    public List<UserMsg> getMsgList(Integer limit) {
        return userMsgMapper.getMsgList(limit);
    }
}
